﻿module Enferno.Public.Web.Components.Controllers.Base {

    export class AccountEvents {
        public static loggedIn: string = "Enferno.Account.Events.LoggedIn";
        public static loggedOut: string = "Enferno.Account.Events.LoggedOut";        
    }

    export class AccountControllerBase {

        public login(loginName: string, password: string, rememberMe: boolean): JQueryPromise<Models.CustomerModel> {
            var deferred = jQuery.Deferred<Models.CustomerModel>();

            var data = { loginName: loginName, password: password, isPersisted: rememberMe };

            var url = UrlHelper.getUrl(AccountServices.Login);

            $.post(url, data).then(serverCustomer => {
                var userModel = new Models.CustomerModel(serverCustomer);
                $.Event(AccountEvents.loggedIn, userModel);
                deferred.resolve(userModel);
            });

            return deferred.promise();
        }

        public logout(): JQueryPromise<void> {
            var deferred = jQuery.Deferred<void>();

            var url = UrlHelper.getUrl(AccountServices.Logout);

            $.post(url).then(() => {
                $.Event(AccountEvents.loggedOut);
                deferred.resolve();
            });

            return deferred.promise();
        }

        public getPersonInfo(socialSecurityNumber: string): JQueryPromise<Models.AddressAndPersonInformationModel> {
            var deferred = jQuery.Deferred<Models.AddressAndPersonInformationModel>();

            var data = { socialSecurityNumber: socialSecurityNumber };

            var url = UrlHelper.getUrl(AccountServices.GetCustomerInfo);

            $.get(url, data).then(
                info => { //success
                    var model = new Models.AddressAndPersonInformationModel(info);
                    deferred.resolve(model);
                }, error => { //error
                    console.error(error.statusText);
                    deferred.reject(error.statusText);
                });

            return deferred.promise();
        }

        public getCompanyInfo(organisationNumber: string): JQueryPromise<Models.AddressAndCompanyInformationModel> {
            var deferred = jQuery.Deferred<Models.AddressAndCompanyInformationModel>();

            var data = { organisationNumber: organisationNumber };

            var url = UrlHelper.getUrl(AccountServices.GetCompanyInfo);

            $.get(url, data).then(
                info => { //success
                    var model = new Models.AddressAndCompanyInformationModel(info);
                    deferred.resolve(model);
                }, error => { //error
                    console.error(error.statusText);
                    deferred.reject(error.statusText);
                });

            return deferred.promise();
        }

    }

} 